<script setup lang="ts">
import { onMounted, ref } from "vue";
import { TableInstance } from "element-plus";
import EditRemarkIcon from "@/assets/svg/devices/edit_remark.svg";
import StartTestIcon from "@/assets/svg/devices/start_test.svg";
import DeleteDeviceIcon from "@/assets/svg/devices/delete_device.svg";
import { apiDeleteDevice, apiGetDevices, apiUpdateDevice } from "@/api/devices";
import { showMsg } from "@/components/ReMessageBox";
import ReCustomPagination from "@/components/RePagination/custom.vue";

interface DeviceI {
  id: number;
  udid: string;
  name: string;
  imei: string;
  status: string;
  remark?: string;
}

defineOptions({
  name: "DeviceList"
});

const tableData = ref<DeviceI[]>();
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

const getDevices = async (page: number, pageSize: number) => {
  try {
    const params = {
      page: page,
      pageSize: pageSize
    };
    const res = await apiGetDevices(params);
    console.log("res: ", res);
    tableData.value = (await res).data;

    total.value = res.total;
  } catch (error) {
    showMsg(3, error.message);
  }
};

onMounted(async () => {
  await getDevices(currentPage.value, pageSize.value);
});
// 分页切换时恢复选中状态
const updatePage = async (page: number) => {
  currentPage.value = page;
  await getDevices(currentPage.value, pageSize.value);
};

const multipleTableRef = ref<TableInstance>();

const multipleSelection = ref<DeviceI[]>([]);
// todo 哪些可选
const selectable = (row: DeviceI) => !["测试中", "离线"].includes(row.status);
const waitDevice = ref([]);

const handleSelectionChange = (val: DeviceI[]) => {
  // // 移除当前页取消选中的项
};

const getStatusColor = (status: string) => {
  switch (status) {
    case "在线":
    case "online":
      return "#149514";

    case "离线":
    case "offline":
      return "#8A1616";

    case "testing":
    case "测试中":
      return "#2162EA";
    case "未知":
    case "unknown":
      return "#000000";
  }
};

const devTestStart = (device: DeviceI) => {
  console.log(device.imei + "开始测试！");
};

const devDelete = (device: DeviceI | DeviceI[]) => {
  waitDevice.value = [];
  if (!device) {
    return;
  } else if (Array.isArray(device)) {
    // 如果是设备数组，遍历数组中的每个设备
    device.forEach(d => {
      waitDevice.value.push(d.imei);
    });
  } else {
    // 如果是单个设备对象
    waitDevice.value.push(device.imei);
  }

  console.log("待删除的设备：", waitDevice.value);
  deleteDialogVisible.value = true;
};

const deleteDialogVisible = ref(false);
const deleteData = ref();
// todo 删除
const confirmDelete = async (device: any) => {
  try {
    console.log("删除设备：" + device + "成功！");
    await getDevices(currentPage.value, pageSize.value);
    deleteDialogVisible.value = false;
  } catch (error) {
    showMsg(3, error);
  }
};

const getRowKey = (row: any) => row.id;

const getAllSelected = () => {
  const data = multipleTableRef.value.getSelectionRows();
  console.log("所有选中： ", data);
  return data;
};

/*=================================================*/
// 修改remark
const editRemark = (row: any) => {
  row.isEditing = true;
  row.newRemark = row.remark;
};
const submitEdit = async (row: any) => {
  try {
    row.oldRemark = row.remark;
    row.remark = row.newRemark;

    const data = {
      remark: row.remark
    };
    const res = await apiUpdateDevice(row.id, data);
    showMsg(0, "更改成功");
  } catch (err) {
    row.remark = row.oldRemark;
    showMsg(3, err);
  } finally {
    row.isEditing = false;
  }
};
const cancelEdit = (row: any) => {
  try {
  } finally {
    // 还原备注值
    row.isEditing = false;
    row.newRemark = "";
  }
};

const allStartTest = () => {
  const devs = getAllSelected();
  devs.forEach((device: DeviceI) => {
    devTestStart(device);
  });
};

const deleteAllSelected = () => {
  const devs = getAllSelected();
  devs.forEach((device: DeviceI) => {
    apiDeleteDevice(device.id).then(() => {});
  });
};
</script>

<template>
  <div class="page-container">
    <!--<AmPagination :total="22" layout="prev, pager, next" />-->
    <div class="content">
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        :row-key="getRowKey"
        style="width: 100%; height: 550px"
        :header-cell-style="{
          'flex-shrink': 0,
          'border-radius': '5.33px',
          background: '#EFF2F6'
        }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :selectable="selectable" width="55" :reserve-selection="true" />
        <el-table-column prop="id" label="序号" width="180" />
        <el-table-column prop="imei" label="IMEI" width="180" />
        <el-table-column label="设备状态" prop="status">
          <template #default="{ row }">
            <p :style="{ color: getStatusColor(row.status) }">
              {{ row.status }}
            </p>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注">
          <template #default="{ row }">
            <div v-if="!row.isEditing">
              <p>{{ row.remark }}</p>
              <el-button text @click="editRemark(row)">
                <EditRemarkIcon />
              </el-button>
            </div>
            <div v-else>
              <el-input v-model="row.newRemark" size="default" placeholder="请输入备注" style="width: 200px" @keyup.enter="submitEdit(row)" />
              <el-button type="primary" size="small" @click="submitEdit(row)">提交</el-button>
              <el-button size="small" @click="cancelEdit(row)">取消</el-button>
            </div>
          </template>
        </el-table-column>

        <!--  编辑-->
        <el-table-column label="编辑" align="right">
          <template #default="scope">
            <div>
              <el-button size="small" text style="width: 49px; color: #2d3748; font-size: 16px; font-style: normal; font-weight: 400; line-height: 29px" @click="devTestStart(scope.row)">
                <StartTestIcon />
                测试
              </el-button>
              <el-button
                size="small"
                text
                style="
                  width: 49px;
                  color: #8a1616;

                  font-size: 16px;
                  font-style: normal;
                  font-weight: 400;
                  line-height: 29px;
                "
                @click="devDelete(scope.row)"
              >
                <DeleteDeviceIcon />
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <ReCustomPagination :total="total" layout="prev, pager, next" class="am-pagination" @update:pageChange="updatePage" />
    <el-row class="flex justify-center">
      <el-button class="delete-dev-btn" type="danger" @click="devDelete(multipleSelection)">删除</el-button>
      <el-button type="primary" @click="allStartTest">测试</el-button>
    </el-row>
    <el-dialog v-model="deleteDialogVisible" title="提示" center class="delete-dialog">
      <span>确认要删除IMEI：{{ waitDevice }} 设备吗？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="confirmDelete(waitDevice)"> Confirm</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.am-pagination {
  text-align: center; /* 居中对齐分页 */
  padding: 10px 0;
  background: #f5f5f5; /* 可选，添加背景颜色 */
}

::v-deep(.el-dialog) {
  min-height: 300px;
  width: 533.33px;
  height: 346.67px;
  flex-shrink: 0;
  border-radius: 10.67px;
  border: 1.33px solid #d3d3d3;
  background: #fff;
}

::v-deep(.el-dialog__body) {
  min-height: 200px;
}
</style>
